import os
from pathlib import Path
from typing import Callable
from dotenv import load_dotenv
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class EnvFileHandler(FileSystemEventHandler):
    def __init__(self, callback: Callable):
        self.callback = callback
        
    def on_modified(self, event):
        if not event.is_directory and event.src_path.endswith('.env'):
            self.callback()

class EnvManager:
    _instance = None
    _observers = []

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(EnvManager, cls).__new__(cls)
            cls._instance._init()
        return cls._instance

    def _init(self):
        self.env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
        self._setup_file_watcher()
        self.reload_env()

    def _setup_file_watcher(self):
        """设置文件监控"""
        observer = Observer()
        handler = EnvFileHandler(self.reload_env)
        observer.schedule(handler, os.path.dirname(self.env_path), recursive=False)
        observer.start()
    
    def reload_env(self):
        """重新加载环境变量"""
        if os.path.exists(self.env_path):
            # 清除现有环境变量
            for key in list(os.environ.keys()):
                if key.startswith('APP_'):  # 只清除应用相关的环境变量
                    del os.environ[key]
            
            # 重新加载.env文件
            load_dotenv(self.env_path, override=True)
            
            # 通知观察者
            self._notify_observers()

    def add_observer(self, callback: Callable):
        """添加配置变更观察者"""
        if callback not in self._observers:
            self._observers.append(callback)

    def remove_observer(self, callback: Callable):
        """移除配置变更观察者"""
        if callback in self._observers:
            self._observers.remove(callback)

    def _notify_observers(self):
        """通知所有观察者配置已更新"""
        for observer in self._observers:
            observer()

# 创建单例实例
env_manager = EnvManager()
